package com.example.listening.examsdk.core;



import com.example.listening.examsdk.ExamSDK;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Created by tong on 15/11/19.
 */
public class ExamUtil {
    public static final String JSON_PREFIX = "json://";

    public static final String SCOPE_KEY = "ExamUtil_scope_key";
    private static final String QUERY_URL_KEY = "ExamUtil_query_url";
    private static final String FILE_KEY = "ExamUtil_query_file";

    public static JSONObject getJSONObject(String url) {
        //json://Lesson1/Head?file=
        if (!url.startsWith(JSON_PREFIX)) {
            throw new IllegalArgumentException("不支持的协议: " + url);
        }
        StringBuilder builder = new StringBuilder(url);

        url = url.replace(JSON_PREFIX,"");
        String filePath = url.substring(url.indexOf("?file=") + "?file=".length());
        File file = new File(filePath);
        JSONObject jsonObject = getJSONObject(file);
        String[] path = url.substring(0,url.indexOf("?file=")).split("/");

        int idx = 0;
        for (String str : path) {
            jsonObject = jsonObject.optJSONObject(str);
            if (idx == path.length - 1) {
                try {
                    jsonObject.put(SCOPE_KEY,str);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            idx++;
        }
        if (jsonObject != null) {
            try {
                jsonObject.put(QUERY_URL_KEY,builder.toString());
                jsonObject.put(FILE_KEY,file.getAbsolutePath());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static JSONObject getJSONObject(File file) {
        try {
            return (JSONObject)new JSONTokener(getContent(file)).nextValue();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getContent(File file) {
        try {
            ExamSDK.d("load file: " + file.getAbsolutePath());
            return new String(readStream(new FileInputStream(file)));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

    public static byte[] readStream(InputStream is) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            bos.write(buffer,0,len);
        }
        return bos.toByteArray();
    }
}
